package com.gph.saviorframework.config.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.gph.saviorframework.OaConstants;
import com.gph.saviorframework.SaviorFrameworkException;
import com.gph.saviorframework.common.model.Item;
import com.gph.saviorframework.config.service.ItemService;
import com.gph.saviorframework.config.service.SubItemService;
import com.gph.saviorframework.uitl.SecurityUtils;
import com.gph.saviorframework.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("/" + OaConstants.FRAMEWORK_REQUEST_PATH + "/item")
public class ItemController {

    /** 日志输出 */
    final Logger logger = LoggerFactory.getLogger(ItemController.class);

    /** 领域对象名称 */
    private String domain = Item.class.getSimpleName().toLowerCase();

    /** 视图前缀 */
    private String viewPrefix = OaConstants.FRAMEWORK_REQUEST_PATH + "/" + OaConstants.MODULE_CATEGORY_CONFIG + "/" + domain + "/" + domain + "_";

    /** 服务 */
    @Autowired
    private ItemService itemService;

    @Autowired
    private SubItemService subItemService;

    /** 国际化资源 */
    @Autowired
    private MessageSourceAccessor messages;

    @Autowired
    private SecurityUtils securityUtils;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String indexPage() throws SaviorFrameworkException {
        return viewPrefix + "index";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public String list(
            @RequestParam(value = OaConstants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_START) Integer start,
            @RequestParam(value = OaConstants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_SIZE) Integer limit,
            @RequestParam(value = OaConstants.DEFAULT_SORT_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_SORT_FIELD) String sort,
            @RequestParam(value = OaConstants.DEFAULT_DIR_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_SORT_DIRECTION) String dir,
            HttpServletRequest request) throws SaviorFrameworkException {
        String json = "";
        Map<String, Object> params = RequestUtil.getQueryMap(request, itemService.getFields());
        try {
            json = JSONArray.toJSONString(itemService.find(start,limit,sort,dir,params));
            logger.info(messages.getMessage("log.info.list", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain) }));
        }
        catch (DataAccessException e) {
            e.printStackTrace();
            logger.error(messages.getMessage("log.error.list", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain) }));
        }
        return json;
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createPage() throws SaviorFrameworkException {
        return viewPrefix + "create";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public @ResponseBody
    ModelMap create(@ModelAttribute Item item) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            securityUtils.setCreateEntity(item);
            itemService.save(item);
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            modelMap.addAttribute(OaConstants.DEFAULT_ID_KEY, item.getId());
        }
        catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editPage() throws SaviorFrameworkException {
        return viewPrefix + "edit";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap update(@PathVariable("id") String id, HttpServletRequest request) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            Item item = itemService.get(id);
            ServletRequestDataBinder binder = new ServletRequestDataBinder(item);
            binder.bind(request);
            securityUtils.setModifyEntity(item);
            itemService.update(item);
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            modelMap.addAttribute(OaConstants.DEFAULT_ID_KEY, item.getId());
        }
        catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String viewPage() throws SaviorFrameworkException {
        return viewPrefix + "view";
    }

    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ModelMap get(@PathVariable("id") String id) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            modelMap.addAttribute(OaConstants.DEFAULT_RECORD_MODEL_KEY, itemService.findById(id));
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        }
        catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public @ResponseBody
    ModelMap delete(@RequestParam(value = "ids", required = true) String[] ids) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            itemService.deleteByIds(ids);
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        }
        catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/{itemId}/sub", method = RequestMethod.GET)
    @ResponseBody
    public void getSubItem(@PathVariable("itemId") String itemId,HttpServletResponse response) throws SaviorFrameworkException, IOException {
        Object subs = subItemService.findMapByItem(itemId);
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSONArray.toJSONString(subs));
    }
}
